package com.lsongh.springBoot.controller;

import com.lsongh.springBoot.entity.Result;
import com.lsongh.springBoot.entity.User;
import com.lsongh.springBoot.service.UserService;
import com.lsongh.springBoot.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
//import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
@Transactional
public class UserController {

    //引入日志
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    /**
     * 获取所有用户信息
     *
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public Result<User> getAllUser() {
//        return userService.findAll();
        return ResultUtil.success(userService.findAll());
    }

    /**
     * 获取一位用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public Result getOneUser(@PathVariable("id") int id) {

        return ResultUtil.success(userService.findById(id));
    }

    /**
     * 增加一名用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public Result addUser(User user) {
        user.setName(user.getName());
        user.setAge(user.getAge());
        user.setAddress(user.getAddress());
        user.setPassword(user.getPassword());
        user.setSex(user.getSex());
        user.setPhone(user.getPhone());

        return ResultUtil.success(userService.save(user));
    }

    /**
     * 修改一名用户信息
     *
     * @param id
     * @param name
     * @param sex
     * @param age
     * @param phone
     * @param password
     * @param address
     * @return
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public Result updateUser(@PathVariable("id") int id,
                             @RequestParam("name") String name,
                             @RequestParam("sex") String sex,
                             @RequestParam("age") String age,
                             @RequestParam("phone") String phone,
                             @RequestParam("password") String password,
                             @RequestParam("address") String address,
                             @RequestParam("img") MultipartFile[] img) {
        User user = new User();
        user.setId(id);
        user.setSex(sex);
        user.setAge(age);
        user.setName(name);
        user.setPhone(phone);
        user.setAddress(address);
        user.setPassword(password);

        //上传图片设置
        String savePath = "E:\\LSH-project\\img";
        String newFileName = null;
        String filePath = null;
        int size = 0;
        String suffixName = null;
        for (MultipartFile file : img) {
            if (file != null && !file.isEmpty()) {
                //获取文件名称
                String fileName = file.getOriginalFilename();
                //获取后缀名
                suffixName = fileName.substring(fileName.indexOf(".") + 1);
                //图片大小
                size = (int) file.getSize();
                //新文件名称
                newFileName = System.currentTimeMillis() + "." + suffixName;
                //新文件路劲
                filePath = savePath + "\\" + newFileName;
                user.setImg("uploadImg/story/" + newFileName);
                // user.setImg("uploadImg/story/" + newFileName);
                logger.info(">>>>>>>>>>>>>>>>>>>>" + newFileName);
                //获取存储文件路径

                java.io.File fileDir = new java.io.File(savePath);
                if (!fileDir.exists()) {
                    //如果文件夹没有：新建
                    fileDir.mkdirs();
                }
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(filePath);
                    fos.write(file.getBytes());
                    fos.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("失败");
                } finally {
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();

                    }
                }
            }

        }
        return ResultUtil.success(userService.save(user));
    }

    /**
     * 删除一名信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public Result deleteUser(@PathVariable("id") int id) {
        userService.deleteById(id);
        return ResultUtil.success("");
    }

//    @GetMapping("/user/export")
//    public void exportUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        HSSFWorkbook wb = userService.findAll();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
//        String filename = "统计报表"+sdf.format(new Date())+ ".xls";;
//        resp.setContentType("application/ms-excel;charset=UTF-8");
//        resp.setHeader("Content-Disposition", "attachment;filename="
//                .concat(String.valueOf(URLEncoder.encode(filename, "UTF-8"))));
//        OutputStream out = resp.getOutputStream();
//        try {
//            wb.write(out);// 将数据写出去
//            String str = "导出" + filename + "成功！";
//            System.out.println(str);
//        } catch (Exception e) {
//            e.printStackTrace();
//            String str1 = "导出" + filename + "失败！";
//            System.out.println(str1);
//        } finally {
//            out.close();
//        }
//
//    }

}
